package org.example.client.utils;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.InputStream;
import java.security.Key;


/**
*@Description   AES加密解密工具包
*@Author  24025
*@Date  2022/2/18
*/
public class AESUtils {

    /**
     * 加密算法
     */
    private static final String ALGORITHM = "AES";
    /**
     * 密钥的长度
     */
    private static final int KEY_SIZE = 128;

    /**
     * AES解密文件
     */
    public static InputStream decryptFile(String key, InputStream fileInputStream) throws Exception {

        Key k = toKey(Base64Utils.decode(key));
        byte[] raw = k.getEncoded();
        SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        CipherInputStream cin = new CipherInputStream(fileInputStream, cipher);

        return cin;
    }
    /**
     * 转换密钥
     */
    private static Key toKey(byte[] key) {
        SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);
        return secretKey;
    }
}
